﻿var _helper = new Helper();
var editIndex = undefined;
var ATPs;
var OrderDetailSelected;
jQuery(document).ready(function () {

    jQuery('#orderListMenu').addClass('active');
    jQuery('#documentTab').tabs({
        width: 1000,
        border: false,
        onSelect: function (title) {
            switch (title) {
                case "All":
                    break;
                case "Wait for approve":
                    var orderWaitForApprove = jQuery.grep(jQuery('#orderAllList').datagrid('getRows'), function (d, i) {
                        return d.Status == 2
                    });

                    jQuery('#orderWaitForApproveList').datagrid({
                        data: orderWaitForApprove,
                        loadFilter: pagerFilter,
                        onDblClickRow: function (index, fields, value) {
                            OpenOrderDetailsPopup(fields.OrderNo, fields.Status);
                        }
                    });

                    break;
                case "On Queue":
                    var orderOnQueue = jQuery.grep(jQuery('#orderAllList').datagrid('getRows'), function (d, i) {
                        return d.Status == 3
                    });

                    jQuery('#orderOnQueueList').datagrid({
                        data: orderOnQueue,
                        loadFilter: pagerFilter,
                        onDblClickRow: function (index, fields, value) {
                            OpenOrderDetailsPopup(fields.OrderNo, fields.Status);
                        }
                    });
                    break;
                case "Completed":
                    var orderCompleted = jQuery.grep(jQuery('#orderAllList').datagrid('getRows'), function (d, i) {
                        return d.Status == 4
                    });

                    jQuery('#orderWaitForApproveList').datagrid({
                        data: orderCompleted,
                        loadFilter: pagerFilter,
                        onDblClickRow: function (index, fields, value) {
                            OpenOrderDetailsPopup(fields.OrderNo, fields.Status);
                        }
                    });
                    break;
                default:
            }
        }
    });

    jQuery('#orderAllList').datagrid({
        url: "/service/api.ashx?metdhodName=GetOrderAll",
        loadFilter: pagerFilter,
        onDblClickRow: function (index, fields, value) {

            OpenOrderDetailsPopup(fields.OrderNo, fields.Status);
        }
    });



});

function saveDocument(status) {
    var document = jQuery('#orderAllList').datagrid('getSelected');
    var documentDetails = jQuery('#orderDetailsList').datagrid('getRows');
    if (status != undefined || status != '') {
        document.Status = status;
    }
    _helper.SaveDocument(JSON.stringify(document), JSON.stringify(documentDetails), function (result) {
        alert("Save Success");
        jQuery('#orderDetails').dialog('close');
        jQuery('#orderAllList').datagrid('reload');
    });

}

function approveDocument(isApproved) {
    if (isApproved) {
        var document = jQuery('#orderAllList').datagrid('getSelected');
        var documentDetails = jQuery('#orderDetailsList').datagrid('getRows');
        if (status != undefined && status != '') {
            document.Status = status;
        }

        _helper.ApproveOrder(JSON.stringify(document), JSON.stringify(documentDetails), function (result) {
            alert("Save Success");
            jQuery('#orderDetails').dialog('close');
            jQuery('#orderAllList').datagrid('reload');
        });
    }
}

function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = jQuery(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}

function OpenOrderDetailsPopup(orderID, Status) {
    jQuery('#orderDetailsList').datagrid({
        url: "/service/api.ashx?metdhodName=GetOrderDetails&orderId=" + orderID,
        pagination: false,
        onLoadSuccess: function () { updateATP(); },

        onDblClickCell: function (index, field1) {
            if (editIndex != undefined) {
                //jQuery('#orderDetailsList').datagrid('select', editIndex);
                var t = jQuery('#orderDetailsList'); //My treegrid selector
                t.datagrid('endEdit', editIndex);
                editIndex = undefined;
                return;
            }

            editIndex = index;

            //jQuery(this).datagrid('beginEdit', index, field1);
            jQuery(this).datagrid('selectRow', index).datagrid('editCell', { index: index, field: field1 });
            var ed = jQuery(this).datagrid('getEditor',
                                     { index: index, field: field1 });
            if (ed == null) {
                return;
            }
            jQuery(ed.target).focus().select().bind('keyup', function (e) {
                var code = e.keyCode || e.which;
                if (code == 13) { //Enter keycode
                    //Trigger code to save row
                    //This executes onAfterEdit event code
                    var t = jQuery('#orderDetailsList'); //My treegrid selector
                    t.datagrid('endEdit', editIndex, field1);
                    editIndex = undefined; //editIndex is a global var

                }
            });
        }
    });

    switch (Status) {
        case 1:
            jQuery('#UpdateAtpButton').hide();
            jQuery('#panelApprover').hide();
            jQuery('#panelSC').hide();
            break;
        case 2:
            jQuery('#UpdateAtpButton').show();
            jQuery('#panelApprover').show();
            jQuery('#panelSC').hide();

            break;
        case 3:
            jQuery('#UpdateAtpButton').hide();
            jQuery('#panelApprover').hide();
            jQuery('#panelSC').hide();
            jQuery('#orderDetailsList').datagrid('hideColumn', 'MaterialNo');
            break;
        case 4:
            jQuery('#UpdateAtpButton').hide();
            jQuery('#panelApprover').hide();
            jQuery('#panelSC').hide();
            jQuery('#orderDetailsList').datagrid('hideColumn', 'MaterialNo');
            break;

        default:
    }

    jQuery('#orderDetails').dialog('open').dialog('setTitle', 'รายละเอียดใบสั่งซื้อเลขที่ ' + orderID);
}

function openATPDetailsPopup(matNo, updateIndex, ItemId) {
    if (ATPs == undefined) {
        updateATP();
    }
    var apts;
    for (var key in ATPs) {
        if (key == matNo) {
            apts = ATPs[key];
            break;
        }
    }

    if (apts != undefined) {
        jQuery('#AtpDetailsList').datagrid({
            data: apts,
            onDblClickRow: function (i, value) {
                SelectAtp(updateIndex, value);
            }
        });

        jQuery('#selectAtp').linkbutton({
            iconCls: 'icon-save'

        });

        jQuery('#AtpDetails').dialog('open').dialog('setTitle', 'รายละเอียด ATP');

        OrderDetailSelected = updateIndex;
    }
}

function SelectAtp(updateIndex, value) {

    if (updateIndex == undefined) {
        value = jQuery('#AtpDetailsList').datagrid('getSelected');
        updateIndex = OrderDetailSelected;

    }

    if (updateIndex != undefined && value != null) {
        jQuery('#orderDetailsList').datagrid('updateRow', {
            index: updateIndex,
            row: {
                ATP: value.ATPQty,
                Plant: value.Plant
            }
        });
    }
    jQuery('#AtpDetails').dialog('close')
}


function formatLinkATP(val, data, index) {
    if (val === null || val === '') {
        return null;
    }
    else {

        //return '<a href=javascript:openATPDetailsPopup("' + data.ItemId + '");>View ATP </a>';
        return "<a href=javascript:openATPDetailsPopup('" + val + "'," + index + ");>View ATP </a>"
    }
}

function updateATP() {
    var documentDetails = jQuery('#orderDetailsList').datagrid('getRows');
    var prodIds = [];
    jQuery.each(documentDetails, function (i, d) {
        prodIds.push(d.MaterialNo);
    });
    _helper.GetATP(JSON.stringify(prodIds), function (result) {
        ATPs = result;
        jQuery.each(result, function (i, d) {
            var Plant = new filePlantMaxAtp(d);
            var max = Plant.Max;
            var sb = Plant.SumSB;
            var ry = Plant.SumRy;
            var total = Plant.SumTotal;

            for (var i = 0; i < documentDetails.length; i++) {
                if (documentDetails[i].MaterialNo == max.Materialno) {
                    jQuery('#orderDetailsList').datagrid('updateRow', {
                        index: i,
                        row: {
                            ATP: parseFloat(max.ATPQty),
                            Plant: max.Plant,
                            ATPSB: sb,
                            ATPRY: ry,
                            ATPTotal: total
                        }
                    });
                    break;
                }
            };
        });
    });
}

function filePlantMaxAtp(atp) {

    this.Max = {};
    this.SumSB = 0;
    this.SumRy = 0;
    this.SumTotal = 0;

    for (var i = 0; i < atp.length; i++) {
        if (this.Max.ATPQty == undefined || parseFloat(atp[i].ATPQty) > parseFloat(this.Max.ATPQty)) {
            this.Max = atp[i];
        }
        if (atp[i].Location == 'SB') {
            this.SumSB += parseFloat(atp[i].ATPQty);
        }
        else if (atp[i].Location == 'RY') {
            this.SumRy += parseFloat(atp[i].ATPQty);
        }
        this.SumTotal += parseFloat(atp[i].ATPQty);
    }

}
//function onDoubleClickCell(index, field) {
//    if (endEditing()) {
//        jQuery('#orderDetailsList').datagrid('selectRow', index)
//        .datagrid('editCell', { index: index, field: field });
//        editIndex = index;
//    }
//}

function uploadOrder() {
    window.open("/pages/ImportOrder.aspx", "_blank", "toolbar=no, scrollbars=no, resizable=yes, top=500, left=500, width=400, height=400");
}

jQuery.extend(jQuery.fn.datagrid.methods, {
    editCell: function (jq, param) {
        return jq.each(function () {
            var opts = jQuery(this).datagrid('options');
            var fields = jQuery(this).datagrid('getColumnFields', true).concat(jQuery(this).datagrid('getColumnFields'));
            for (var i = 0; i < fields.length; i++) {
                var col = jQuery(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                }
            }
            jQuery(this).datagrid('beginEdit', param.index);
            for (var i = 0; i < fields.length; i++) {
                var col = jQuery(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

//function endEditing() {
//    if (editIndex == undefined) { return true }
//    if (jQuery('#orderDetailsList').datagrid('validateRow', editIndex)) {
//        jQuery('#orderDetailsList').datagrid('endEdit', editIndex);
//        editIndex = undefined;
//        return true;
//    } else {
//        return false;
//    }
//}